 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=107 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:05 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Refactor large Controllers 
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='AbstractRequestParser,Controller,TroubleTicket,WebAction,controller,JSP,servlet,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Refactor large Controllers </div>

<div class='main-body'>
 
<br>Implementations of <tt>HttpServlet</tt> are sometimes informally called <tt>Controller</tt> classes.
They form the entry point of client HTTP requests into a web application.
<tt>Controller</tt> classes should be fairly compact, and their code should in general be at a high level of abstraction. 
<tt>Controller</tt> classes do a lot of work, but most of their work should be performed by <i>delegating</i> to other classes. 
A well designed application will have a <tt>Controller</tt> which is not excessively lengthy.
If you use a framework, the <tt>Controller</tt> class is often defined as part of the framework, and not by your application.

<p>Examples of tasks which can be delegated by the <tt>Controller</tt> to another class include :
<ul>
<li>
translating raw user requests into problem domain objects</li>

<li>
logging user request statistics</li>

<li>
validating user input</li>

<li>
interacting with the database</li>

<li>
ensuring necessary objects are in scope for subsequent display</li>

<li>
forwarding to a JSP for display to the user</li>

<li>
handling any exceptions thrown by the application</li>
</ul>

<h4>Example</h4>

Here is part of the <tt>Controller</tt> from the WEB4J framework. It delegates most of its work to :
<ul>
<li>a <tt>RequestParser</tt>, a higher level wrapper around the underlying request
<li>an implementation of an <tt>Action</tt> interface</li>
<li>a <tt>ResponsePage</tt>, to represent the final page served to the user</li>
<li>an <tt>ApplicationFirewall</tt>, to verify basic sanity of the request</li>
<li>a <tt>TroubleTicket</tt>, to gather diagnostic information, and email it to the webmaster</li>
</ul>
<br>
<PRE>

<span class='comment'>/**
* Controller that delegates to various framework classes.
*/</span>
<span class='keyword'>public</span> <span class='keyword'>class</span> Controller <span class='keyword'>extends</span> HttpServlet {

  <span class='comment'>//..elided
</span>  
  <span class='comment'>/** Call {@link #processRequest}.  */</span>
  <span class='keyword'>@Override</span> <span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>void</span> doGet(
   HttpServletRequest aRequest, HttpServletResponse aResponse
  ) <span class='keyword'>throws</span> ServletException, IOException {
    processRequest(aRequest, aResponse);
  }

  <span class='comment'>/** Call {@link #processRequest}.  */</span>
  <span class='keyword'>@Override</span> <span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>void</span> doPost(
    HttpServletRequest aRequest, HttpServletResponse aResponse
  ) <span class='keyword'>throws</span> ServletException, IOException {
    processRequest(aRequest, aResponse);
  }

  <span class='comment'>/**
  * Handle all HTTP &lt;tt&gt;GET&lt;/tt&gt; and &lt;tt&gt;POST&lt;/tt&gt; requests.
  * 
  * &lt;P&gt;This method can be overridden, if desired. Most applications will not need 
  * to override this method. 
  * 
  * &lt;P&gt;Operations include :
  * &lt;ul&gt;
  * &lt;li&gt;set the request character encoding to the value configured in &lt;tt&gt;web.xml&lt;/tt&gt;
  * &lt;li&gt;get an instance of {@link RequestParser}
  * &lt;li&gt;get its {@link Action}, and execute it
  * &lt;li&gt;perform either a forward or a redirect to its  
  * {@link hirondelle.web4j.action.ResponsePage}
  * &lt;li&gt;if an unexpected problem occurs, create a {@link TroubleTicket}, log it, and 
  * email it to the webmaster email address configured in &lt;tt&gt;web.xml&lt;/tt&gt;
  * &lt;li&gt;if the response time exceeds a configured threshold, build a 
  * {@link TroubleTicket}, log it, and email it to the webmaster address configured 
  * in &lt;tt&gt;web.xml&lt;/tt&gt;
  * &lt;/ul&gt;
  */</span>
  <span class='keyword'>protected</span> <span class='keyword'>void</span> processRequest(
    HttpServletRequest aRequest, HttpServletResponse aResponse
  ) <span class='keyword'>throws</span> ServletException, IOException {
    Stopwatch stopwatch = <span class='keyword'>new</span> Stopwatch();
    stopwatch.start();
   
    RequestParser requestParser = RequestParser.getInstance(aRequest, aResponse);
    <span class='keyword'>try</span> {
      Action action = requestParser.getWebAction();
      ApplicationFirewall appFirewall = BuildImpl.forApplicationFirewall();
      appFirewall.doHardValidation(action, requestParser);
      ResponsePage responsePage = action.execute();
      <span class='keyword'>if</span> ( responsePage.getIsRedirect() ) {
        redirect(responsePage, aResponse);
      }
      <span class='keyword'>else</span> {
        forward(responsePage, aRequest, aResponse);
      }
    }
    <span class='keyword'>catch</span> (BadRequestException ex){
      <span class='keyword'>if</span>( Util.textHasContent(ex.getErrorMessage()) ){
        aResponse.sendError(ex.getStatusCode(), ex.getErrorMessage());      
      }
      <span class='keyword'>else</span> {
        aResponse.sendError(ex.getStatusCode());      
      }
    }
    <span class='keyword'>catch</span> (Throwable ex) {
      <span class='comment'>//Bugs OR rare conditions, for example datastore failure
</span>      logAndEmailSeriousProblem(ex, aRequest);
      aResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    }
   
    stopwatch.stop();
    <span class='keyword'>if</span> ( stopwatch.toValue() >= fPOOR_PERFORMANCE_THRESHOLD ) {
      logAndEmailPerformanceProblem(stopwatch.toValue(), aRequest);
    }
  }
  
  
  <span class='comment'>/**
  * Inform the webmaster of an unexpected problem with the deployed application.
  * 
  * &lt;P&gt;Typically called when an unexpected &lt;tt&gt;Exception&lt;/tt&gt; occurs in 
  * {@link #processRequest}. Uses {@link TroubleTicket#mailToWebmaster}.
  * 
  *  &lt;P&gt;Also, stores the trouble ticket in application scope, for possible 
  *  later examination. 
  */</span>
  <span class='keyword'>protected</span> <span class='keyword'>final</span> <span class='keyword'>void</span> logAndEmailSeriousProblem (
    Throwable ex, HttpServletRequest aRequest
  ) <span class='keyword'>throws</span> AppException {
    TroubleTicket troubleTicket = <span class='keyword'>new</span> TroubleTicket(ex, aRequest);
    fLogger.severe(<span class='literal'>"TOP LEVEL CATCHING Throwable"</span>);
    fLogger.severe( troubleTicket.toString() ); 
    log(<span class='literal'>"SERIOUS PROBLEM OCCURRED."</span>);
    log( troubleTicket.toString() );
    aRequest.getSession().getServletContext().setAttribute(
      MOST_RECENT_TROUBLE_TICKET, troubleTicket
    );
    troubleTicket.mailToWebmaster();
  }

  <span class='comment'>/**
  * Inform the webmaster of a performance problem.
  * 
  * &lt;P&gt;Called only when the response time of a request is above the threshold 
  * value configured in &lt;tt&gt;web.xml&lt;/tt&gt;.
  * 
  * &lt;P&gt;Builds a &lt;tt&gt;Throwable&lt;/tt&gt; with a description of the problem, then creates and 
  * emails a {@link TroubleTicket} to the webmaster.
  * 
  * @param aMilliseconds response time of a request in milliseconds
  */</span>
  <span class='keyword'>protected</span> <span class='keyword'>final</span> <span class='keyword'>void</span> logAndEmailPerformanceProblem(
    <span class='keyword'>long</span> aMilliseconds, HttpServletRequest aRequest
  ) <span class='keyword'>throws</span> AppException {
    String message = 
      <span class='literal'>"Response time of web application exceeds configured performance threshold."</span> 
      + NEW_LINE + 
      <span class='literal'>"Time : "</span> + aMilliseconds + <span class='literal'>" milliseconds."</span>
    ;
    Throwable ex = <span class='keyword'>new</span> Throwable(message);
    TroubleTicket troubleTicket = <span class='keyword'>new</span> TroubleTicket(ex, aRequest);
    fLogger.severe(<span class='literal'>"Poor response time : "</span> + aMilliseconds + <span class='literal'>" milliseconds"</span>);
    fLogger.severe( troubleTicket.toString() ); 
    log(<span class='literal'>"Poor response time : "</span> + aMilliseconds + <span class='literal'>" milliseconds"</span>);
    log( troubleTicket.toString() );
    troubleTicket.mailToWebmaster();
  }

  <span class='comment'>//..elided
</span>}
 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicActiona7f6-2.html?Id=108'>Use Model-View-Controller framework</a> <br>
 
  
  <a href='TopicAction703a-2.html?Id=138'>Parse parameters into domain objects</a> <br>
 
  
  <a href='TopicActionae2d-2.html?Id=139'>Command objects</a> <br>
 
  
  <a href='TopicActionc3f2-2.html?Id=179'>Send trouble-ticket emails</a> <br>
 
  
  <a href='TopicAction5f31-2.html?Id=188'>A Web App Framework - WEB4J</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='107'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=107 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:05 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
